<!-- 定额管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 分类树 -->
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <NormCategoryTree ref="categoryTreeRef" v-model="queryParams.categoryIds" @node-click="handleQuery" />
      </el-col>

      <!-- 定额列表 -->
      <el-col :lg="20" :xs="24">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
            <el-form-item label="关键字" prop="keywords">
              <el-input v-model="queryParams.keywords" placeholder="定额名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar">
            <div class="data-table__toolbar--actions">
              <el-button type="primary" plain icon="plus" @click="handleOpenDialog()">
                新增
              </el-button>
            </div>
          </div>

          <el-table v-loading="loading" :data="pageData" border stripe highlight-current-row
            class="data-table__content">
            <el-table-column label="定额项" prop="name" />
            <el-table-column label="定额分类" width="150" align="center" prop="categoryName" />
            <el-table-column label="价格" width="120" align="right" prop="price">
              <template #default="scope">
                {{ `￥${scope.row.price}` }}
              </template>
            </el-table-column>
            <el-table-column label="单位" align="center" prop="unit" width="120" />
            <el-table-column label="描述" prop="remark" />
            <el-table-column label="操作" fixed="right" width="220">
              <template #default="scope">
                <el-button type="primary" :disabled="!!scope.row.systemd" icon="edit" link size="small"
                  @click="handleOpenDialog(scope.row.id)">
                  编辑
                </el-button>
                <el-button type="danger" :disabled="!!scope.row.systemd" icon="delete" link size="small"
                  @click="handleDelete(scope.row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="fetchData" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 定额表单 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" @close="handleCloseDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="定额项" prop="name">
          <el-input v-model="formData.name" :disabled="!!formData.id" :readonly="!!formData.id" placeholder="定额项" />
        </el-form-item>


        <el-form-item label="定额分类" prop="categoryId">
          <el-tree-select v-model="formData.categoryId" placeholder="请选择定额分类" :data="deptOptions" filterable
            check-strictly :render-after-expand="false" />
        </el-form-item>

        <el-form-item label="材料编码" prop="code">
          <el-input :disabled="!!formData.id" v-model="formData.code" placeholder="请输入编码，不输入则自动生成" />
        </el-form-item>

        <el-form-item label="市场价格" prop="price">
          <el-input-number v-model="formData.price" :precision="2" :step="1" :min="1">
            <template #prefix>
              <span>￥</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="成本价格" prop="costPrice">
          <el-input-number v-model="formData.costPrice" :precision="2" :step="1" :min="1">
            <template #prefix>
              <span>￥</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="单位" prop="unit">
          <el-input v-model="formData.unit" placeholder="请输入单位" maxlength="50" />
        </el-form-item>

        <el-form-item label="描述" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入描述" maxlength="50" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";
import NormAPI, { NormForm, NormPageQuery, NormPageVO } from "@/api/business/material/norm.api";
import NormCategoryTree from "./components/NormCategoryTree.vue";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const appStore = useAppStore();

const categoryTreeRef = ref();
const queryFormRef = ref();
const userFormRef = ref();

const pageData = ref<NormPageVO[]>();
const total = ref(0);
const queryParams = reactive<NormPageQuery>({
  pageNum: 1,
  pageSize: 10,
});
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增定额",
});

const formData = reactive<NormForm>({
  price: 1,
});

const rules = reactive({
  name: [{ required: true, message: "定额名不能为空", trigger: "blur" }],
  price: [{ required: true, message: "定额价格不能为空", trigger: "blur" }],
  costPrice: [{ required: true, message: "定额成本价格不能为空", trigger: "blur" }],
  code: [{ required: true, message: "定额编码不能为空", trigger: "blur" }],
  categoryId: [{ required: true, message: "定额分类不能为空", trigger: "blur" }],
});

// 选中的定额ID
const selectIds = ref<number[]>([]);
// 分类下拉数据源
const deptOptions = ref<OptionType[]>();

// 获取数据
async function fetchData() {
  loading.value = true;
  try {
    const data = await NormAPI.getPage(queryParams);
    pageData.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  if (queryParams.categoryIds) {
    queryParams.deepSearch = true;
  }
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

/**
 * 打开弹窗
 *
 * @param id 定额ID
 */
async function handleOpenDialog(id?: string) {
  dialog.visible = true;

  // 加载分类下拉数据源
  deptOptions.value = categoryTreeRef.value.deptList;

  if (id) {
    dialog.title = "修改定额";
    NormAPI.getFormData(id).then((data) => {
      Object.assign(formData, { ...data, price: parseFloat(data.price || "1") });
    });
  } else {
    formData.categoryId = queryParams.categoryIds;
    dialog.title = "新增定额";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
}

// 提交定额表单
const handleSubmit = () => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        NormAPI.update(formData)
          .then(() => {
            ElMessage.success("修改定额成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        NormAPI.create(formData)
          .then(() => {
            ElMessage.success("新增定额成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
};

/**
 * 删除定额
 *
 * @param id  定额ID
 */
function handleDelete(id: string) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除定额?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      NormAPI.deleteById(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}
</script>
